package com.zhuhao.threaddemo;

import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author zhuhao
 * @Date 2022/6/1 10:01
 * @desc
 */
public class ThreadTest {

    /**
     * 实现 Runnable 接口，没有返回值
     */
    @Test
    public void runnableTest() {
        RunnableDemo demoRunnable = new RunnableDemo();
        Thread thread = new Thread(demoRunnable);
        thread.start();
    }

    /**
     * Callable 1.call方法有返回值，run方法没有 2.call方法可以抛出异常，run方法不行
     */
    @Test
    public void callableTest() throws ExecutionException, InterruptedException {
        CallableDemo callableDemo = new CallableDemo();
        FutureTask<String> stringFutureTask = new FutureTask<>(callableDemo);
        Thread thread = new Thread(stringFutureTask);
        thread.start();
        System.out.println(stringFutureTask.get());
    }

    /**
     * 继承thread
     * 实现接口会更好一些，Java 不支持多重继承，因此继承了 Thread 类就无法继承其它类，但是可以实现多个接口
     * 类可能只要求可执行就行，继承整个 Thread 类开销过大
     */
    @Test
    public void threadTest() {
        ThreadDemo threadDemo = new ThreadDemo();
        threadDemo.start();
    }

    /**
     * .
     * 著作权归https://pdai.tech所有。
     * 链接：https://pdai.tech/md/java/thread/java-thread-x-thread-basic.html
     * <p>
     * 通过调用一个线程的 interrupt() 来中断该线程，如果该线程处于阻塞、限期等待或者无限期等待状态，那么就会抛出 InterruptedException，
     * 从而提前结束该线程。但是不能中断 I/O 阻塞和 synchronized 锁阻塞。
     */
    @Test
    public void interruptTest() throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.start();
        Thread.sleep(1);
        myThread.interrupt();
        System.out.println("main run");
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            //循环体中使用 interrupted() 方法来判断线程是否处于中断状态，从而提前结束线程
            while (!interrupted()) {
                System.out.println("no interrupted");
            }
            try {
                Thread.sleep(111);
                System.out.println("thread run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
